<template>
  <div class="login-views">
    <van-nav-bar title="登录" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit">
      <van-field
        name="mobile"
        v-model="mobile"
        required
        type="text"
        label="手机号"
      />
      <van-field
        name="code"
        v-model="code"
        required
        center
        clearable
        label="验证码"
        placeholder="请输入短信验证码"
      >
        <template #button>
          <van-button
            @click.prevent="getCode"
            class="vant-button-green"
            size="small"
            type="primary"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div class="btn-box">
        <van-button type="primary" round block>登录</van-button>
      </div>
    </van-form>
  </div>
</template>
<style lang="less">
.login-views {
  .vant-button-green {
    background: #07c160;
  }
  .btn-box {
    padding: 20px;
  }
}
</style>
<script>
//
import { getCode, login, userGetInfo } from "@/api/user.js";
import { mapState } from "vuex";
export default {
  name: "login",
  data() {
    return {
      mobile: "",
      code: ""
    };
  },
  computed: {
    ...mapState(["tokenInfo"])
  },
  // mounted (){
  //     // userGetInfo()
  // },
  methods: {
    onClickLeft() {
      this.$router.back();
    },
    async getCode() {
      // loading
      let mobile = this.mobile;
      this.$toast.loading({
        message: "发送中...",
        forbidClick: true,
        mask: true, // 整体添加一个遮罩
        duration: 0
      });

      try {
        await getCode(mobile);
        //console.log(res)
        this.$toast.loading({
          message: "发送成功", // 提示文字
          forbidClick: true,
          mask: true // 整体添加一个遮罩
        });
      } catch (err) {
        this.$toast.loading({
          message: "发送失败", // 提示文字
          forbidClick: true,
          mask: true // 整体添加一个遮罩
        });
      }
    },
    async onSubmit(obj) {
      //console.log('提交表单',obj)
      this.$toast.loading({
        message: "登录中...",
        forbidClick: true,
        mask: true, // 整体添加一个遮罩
        duration: 0
      });
      // 跳转到其他页面
      try {
        const res = await login(obj);
        //console.log(res)
        this.$store.commit("saveToken", res.data.data);
        this.$toast.loading({
          message: "登录成功", // 提示文字
          forbidClick: true,
          mask: true // 整体添加一个遮罩
        });
        const backto = this.$route.query.backto || "/";
        this.$router.push(backto);
      } catch (err) {
        this.$toast.loading({
          message: "登录中失败", // 提示文字
          forbidClick: true,
          mask: true // 整体添加一个遮罩
        });
      }
    }
  }
};
</script>
